//依赖模块
var fs = require('fs');
var request = require("request");
var cheerio = require("cheerio");
var mkdirp = require('mkdirp');
var async = require('async');

// 目标网址
// var url = 'http://desk.zol.com.cn/meinv/1920x1080/3.html';
var url = 'https://www.google.com.hk/search?newwindow=1&safe=strict&biw=1005&bih=974&tbm=isch&sa=1&ei=pA58Wr7dGYLZ0gTswLXwAQ&q=%E7%BE%8E%E5%A5%B3&oq=%E7%BE%8E%E5%A5%B3&gs_l=psy-ab.3...0.0.0.5523.0.0.0.0.0.0.0.0..0.0....0...1c..64.psy-ab..0.0.0....0.ri3oDMqQ-O0';

// 本地存储目录
var dir = './images';

// 图片链接地址
var links = [];

// 创建目录
mkdirp(dir, function (err) {
    if (err) {
        console.log(err);
    }
});

// 发送请求
request(url, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var $ = cheerio.load(body);
        // $('.photo-list-padding a img').each(function () {
        $('.rg_bx a img').each(function () {
            var src = $(this).attr('src');
            // src = src.replace(/t_s208x130c5/, 't_s1920x1080c5');
            links.push(src);
        });
        // 每次只执行一个异步操作
        async.mapSeries(links, function (item, callback) {
            download(item, dir, Math.floor(Math.random() * 1000) + item.substr(-4, 4));
            callback(null, item);
        }, function (err, results) {});
    }
});

// 下载方法
var download = function (url, dir, filename) {
    request.head(url, function (err, res, body) {
        request(url).pipe(fs.createWriteStream(dir + "/" + filename));
    });
};